/*!
 @header MoreViewController.m
 @abstract 给用户提供和显示农户宝的额外的功能与服务，包括个人信息、用户认证（未上线）、卖家服务、账户信息、新版本检测和关于农户宝
 @author 周益
 @version 1.00 2013/02/21 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "MoreViewController.h"
#import "Config.h"
#import "Option.h"
#import "DBKit.h"
#import "Helper.h"
#import "UserInfoViewController.h"
#import "AboutViewController.h"
#import "SellerServiceViewController.h"
#import "AccountInfoViewController.h"
#import "JMFBase.h"
#import "StatisticsUtil.h"
#import "APService.h"
#import "SplashViewController.h"
#import "announceListViewController.h"
#import "VersionManager.h"
#import "ConsigneeListViewController.h"
#import "MobileFormViewController.h"
#import "UMFeedback.h"
#import "UMFeedbackViewController.h"
#import "HPopupView.h"

#define WORDS_LABEL @"<font color='#86b60e'>购买商品前请先充值<br>出售商品前请先充值并开通卖家服务</font>"

//  -业务逻辑细节说明-
//
//
//  @abstract       View布局
//
//  @discussion     页面实现为功能tableview和注销button
//
//  @notes



//  @abstract       注销功能，用户在点击注销按钮时会注销当前用户账号以及相关服务。
//
//  @discussion     同时要完成用户的账号注销和JPush服务注销。
//
//  @notes          JPush服务是和用户的账号绑定的，所以一定要注销JPush，以防出现用户重复收到推送消息。



//  @abstract       检查更新功能，提供手动检查APP的最新版本。
//
//  @discussion     实现MobClickDelegate，实现- (void)appUpdate:(NSDictionary *)appUpdateInfo方法，新版本信息就在appUpdateInfo字典对象内。
//                      通过判断字典对象中的key“update”的值是否为“YES”或者“NO”来判断是否有更新，如果为YES时，表示APP有更新，否则无最新版本。
//                      当有最新版本时，可以获取version（版本号）、path（更新APP的URL）和updateLog（此次更新版本的LOG）等信息。此时会弹出一个alertview，
//                      会向用户确认是否更新，点击是，会通过path访问相应的下载地址，否则取消更新。
//  @notes


//  -类修改日志-
//  修改人   修改时间   针对版本
//  修改描述

@interface MoreViewController ()  <UMFeedbackDataDelegate>
{
    NSArray *_infoItems;
    NSString *_amountString;
    
    UIImage *_avatarImage;
    
    NSString *_certString;
    
    UMFeedback *_umFeedback;
    
    UMFeedbackViewController *_umfeedbackVC;
}
@end

@implementation MoreViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        _infoItems = @[_L(@"vc_title_048"),_L(@"vc_title_049"),_L(@"vc_title_096"),_L(@"vc_title_011"),_L(@"title_76"),_L(@"title_38"),_L(@"vc_title_097"),_L(@"vc_title_052")];
    }
    return self;
}

- (void)dealloc
{
    _amountString = nil;
    _infoItems = nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setTitle:_L(@"vc_title_047")];   //更多
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    _infoTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, _SYS_FRAME_HEIGHT-100.0f)];
    if (iPhone5) {
        _infoTableView.frame = CGRectMake(0.0f, 0.0f, 320.0f, (_infoItems.count)*44.0f + 60.0f+1136-960);
        
    }
    _infoTableView.delegate = self;
    _infoTableView.dataSource = self;
    [self.view addSubview:_infoTableView];
    
    //退出按钮
    UIButton* logoutButton = [[UIButton alloc] initWithFrame:CGRectMake(10.0f, 20.0f, 300.0f, 40.0f)];
    logoutButton.titleLabel.font = _SYS_FONT_009;
    [logoutButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_007_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [logoutButton setTitle:_L(@"btn_yes_14") forState:UIControlStateNormal];   //退出登录
    [logoutButton addTarget:self action:@selector(logoutButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *logoutView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 60.0f)];
    [logoutView addSubview:logoutButton];
    _infoTableView.tableFooterView = logoutView;

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self personalInfoRequest];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _infoItems.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    
    //信息标签
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 5.0f, 150.0f, 30.0f)];
    label.font = _SYS_FONT_007;
    [cell.contentView addSubview:label];
    
    label.text = _infoItems[indexPath.row];
    
    //渲染cell
    switch (indexPath.row) {
        case 0:
        {
            //第一行为个人信息
   
            //设置用户头像
            _avartImageView = [[UIImageView alloc] initWithFrame:CGRectMake(320.0f - 40.0f - 35.0f, 4.5f, 35.0f, 35.0f)];
            _avartImageView.image = _avatarImage;
            [cell.contentView addSubview:_avartImageView];
        }
            
            break;
        case 1:
        {
            //第二行为账户信息

            _amountLabel = [[UILabel alloc] initWithFrame:CGRectMake(320.0f - 40.0f - 115.0f, 12.0f, 115.0f, 20.0f)];
            _amountLabel.textAlignment = UITextAlignmentRight;
            _amountLabel.textColor = _SYS_COLOR_002;
            _amountLabel.font = _SYS_FONT_004;
            _amountLabel.text = _amountString;
            [cell.contentView addSubview:_amountLabel];
        }
            
            break;
        case 5:
        {
            //第6行为新版本检测
            
            _versionLabel = [[UILabel alloc] initWithFrame:CGRectMake(320.0f - 40.0f - 75.0f, 12.0f, 75.0f, 20.0f)];
            _versionLabel.textAlignment = UITextAlignmentRight;
            _versionLabel.textColor = _SYS_COLOR_002;
            _versionLabel.font = _SYS_FONT_004;
            _versionLabel.text = _L(@"title_40");
            [cell.contentView addSubview:_versionLabel];
        }
            
            break;
        case 7:
        {
            //第7行为关于农户宝

            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(320.0f - 40.0f - 35.0f, 4.5f, 35.0f, 35.0f)];
            imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"more_icon_002@2x" ofType:@"png"]];
            [cell.contentView addSubview:imageView];
        }
            break;
        default:
            break;
    }

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (indexPath.row == 4) {
//        return 50.0f;
//    }
    return 44.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            //点击个人信息栏，push到个人信息页面
            UserInfoViewController *userInfoVC = [[UserInfoViewController alloc] initWithStyle:UITableViewStyleGrouped];
            userInfoVC.delegate = self;
            [userInfoVC.navigationItem setTitle:_infoItems[indexPath.row]];
            userInfoVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:userInfoVC animated:YES];
        }
            
            break;
        case 1:
        {
            //第四行为账户信息
            AccountInfoViewController *accountInfoVC = [[AccountInfoViewController alloc] init];
            [accountInfoVC.navigationItem setTitle:_infoItems[indexPath.row]];
            accountInfoVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:accountInfoVC animated:YES];
        }
            
            break;
        case 2:
        {
            //修改密码被点击
            MobileFormViewController *mobileFormVC = [[MobileFormViewController alloc] init];
            [mobileFormVC.navigationItem setTitle:_infoItems[indexPath.row]];
            
            [mobileFormVC setHidesBottomBarWhenPushed:true];
            //设置是否是忘记密码还是注册，以便设定密码视图区分是设定注册密码还是找回密码
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isRegisterOrNot"];
            [self.navigationController pushViewController:mobileFormVC animated:YES];
        }
            
            break;
        case 3:
        {
            //地址管理被点击
            ConsigneeListViewController* consigneeListViewController = [[ConsigneeListViewController alloc] init];
            [consigneeListViewController setHidesBottomBarWhenPushed:true];
            
            [self.navigationController pushViewController:consigneeListViewController animated:true];
        }
            
            break;
        case 4:
        {
            announceListViewController *announceListVC = [[announceListViewController alloc] initWithStyle:UITableViewStyleGrouped];
            [announceListVC.navigationItem setTitle:_infoItems[indexPath.row]];
            announceListVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:announceListVC animated:YES];
            
        }
            break;
        case 5:
        {
            //第五行为新版本检测
            _HUD = [[MBProgressHUD alloc] initWithView:self.view.window];
            _HUD.alpha = 1.0f;
            [self.view.window addSubview:_HUD];
            _HUD.labelText = _L(@"title_loading_09");
            [_HUD show:YES];
            
            [self checkVersion];
        }
            
            break;
        case 6:
        {
            //第六行为在线客服
            
            
            if (_umfeedbackVC == nil) {
                _umfeedbackVC = [[UMFeedbackViewController alloc] initWithNibName:@"UMFeedbackViewController" bundle:nil];
            }
            _umfeedbackVC.appkey = _SYS_UMENG_APPKEY;
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:_umfeedbackVC];
            navigationController.navigationBar.barStyle = UIBarStyleBlack;
            navigationController.navigationBar.translucent = NO;
            [self presentModalViewController:navigationController animated:YES];
        }
            break;
        case 7:
        {
            //第六行为关于农户宝
            AboutViewController *aboutVC = [[AboutViewController alloc] init];
            [aboutVC.navigationItem setTitle:_infoItems[indexPath.row]];
            aboutVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:aboutVC animated:YES];
        }
            break;
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 私有方法

/*!
 @abstract 向服务器请求用户个人信息
 */
- (void)personalInfoRequest
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_U_GET_BASICINFO];
    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");

    [request setValue:_ACCOUNT_ID forParameter:@"userId"];
    [request asynchronous];
}

/*!
 @abstract 向服务器请求用户个人账户信息
 */
- (void)accountRequest
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ACCOUNT_GET_ACCOUNT];
    request.delegate = self;
    [request setSuccessSelector:@selector(accountRequestSuccess:)];
    [request asynchronous];
}

#pragma mark - 自定义事件

/*!
 @abstract 注销用户
 */
- (void)logoutButtonEvent
{
    [Helper logout];
}

- (void)checkVersion
{
    NSString *curVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];
    NSInteger version = [[curVersion stringByReplacingOccurrencesOfString:@"." withString:@""] integerValue];
    
    _versionInfo = [VersionManager startVersionChecking:version];
    [_HUD hide:true];

    //如果是返回的nil（服务器返回出错），或无更新
    if (_versionInfo == nil || [_versionInfo[@"status"] intValue] == 0) {
        
        [Helper showAlertWithTitle:_L(@"title_81") andMessage:nil];
        return;
    }
    
    UpgradeLevel upgradeLevel = [_versionInfo[@"status"] integerValue];

    NSString *title = [NSString stringWithFormat:_L(@"tpl_38"), @""];
    NSString *message = _versionInfo[@"description"];
    _appPath = _versionInfo[@"download"];
    
    HPopupView* popupView = [[HPopupView alloc] init];
    popupView.titleText = title;
    popupView.contentText = message;
    
    if (upgradeLevel == UpgradeOptionalLevel) {
        
        popupView.cancelButtonTitle = _L(@"btn_back_02");
        [popupView addButtonTitlt:_L(@"btn_yes_27")];
        [popupView addButtonTitlt:_L(@"btn_yes_28")];
        
    }
    //强制升级，只显示“立刻升级”
    else if (upgradeLevel == UpgradeRequiredLevel) {
        
        popupView.cancelButtonTitle = _L(@"btn_yes_27");
    }
    
    [popupView setWillShowBlock:^(UIView *view) {
        
        ((UILabel *)view.subviews[1]).textAlignment = UITextAlignmentLeft;
    }];
    [popupView show];
    
    [popupView setButtonClickedBlock:^BOOL(UIView *view, NSInteger buttonIndex) {
        
        BOOL result = true;  //默认消除弹出框
        
        UpgradeLevel upgradeLevel = [_versionInfo[@"status"] integerValue];
        
        if (buttonIndex == 0) {
            
            //非强制升级下，此时为“以后再说”
            if (upgradeLevel == UpgradeOptionalLevel) {
                
                //用户点击过以后再说后，那么在当前版本下就不再提示用户升级这次的版本
                //接着在这次版本更新中，用户每次启动APP时，先读取数据库中的这个版本值，版本请求过后就判断最新的是不是同一个版本，如果是，就不再提示，否则就提示，并且更改这个值
                [[NSUserDefaults standardUserDefaults] setInteger:[_versionInfo[@"sequence"] integerValue] forKey:@"newestVersion"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            
            //强制升级下，此时为“立刻去升级”
            else if (upgradeLevel == UpgradeRequiredLevel) {
                
                if (_appPath != nil && _appPath.length != 0) {
                    
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_appPath]];
                }
                
                result = false;
            }
        }
        
        //立刻升级
        else if (buttonIndex == 1) {
            
            if (_appPath != nil && _appPath.length != 0) {
                
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_appPath]];
            }
        }
        
        return result;
    }];
}

#pragma mark - accountRequest selector

- (void)accountRequestSuccess:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        NSDictionary* info = [dict valueForKey:@"data"];
        
        //设置账户余额
        _amountString = [NSString stringWithFormat:_L(@"title_amount_06"), [[info valueForKey:@"balance"] floatValue]];

//        [_infoTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
        [_infoTableView reloadData];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }

}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
//    NSLog(@"more....>%@", dict);
    if (jmf.status == JMStatusSucceed) {
        
        NSDictionary* info = [dict valueForKey:@"data"];

        //头像
        _avatarImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[info valueForKey:@"previewAvatar"]]]];
        //卖家等级

        _certString = [info valueForKey:@"certStatus"];

        //串行请求。解决被T出时，反复提示被T出的框框
        [self accountRequest];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
    
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - UserAuthPickerViewController Delegate

- (void)receivingUserAuthType:(NSString *)authType
{
    _certLabel.text = authType;
}

#pragma mark - UserInfoViewController Delegate

- (void)avatarViewShouldReload:(UIImage *)image
{
    _avartImageView.image = image;
}

#pragma mark UIAlertView Delegate

- (void)willPresentAlertView:(UIAlertView *)alertView
{
    if (![_HUD isHidden]) {
        [_HUD hide:YES];
        [_HUD removeFromSuperview];
    }
    
//    if ([alertView.subviews[2] isKindOfClass:[UILabel class]]) {
//        
//        ((UILabel *)alertView.subviews[2]).textAlignment = NSTextAlignmentLeft;
//    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    UpgradeLevel upgradeLevel = [_versionInfo[@"status"] integerValue];
    
    if (buttonIndex == 0) {
        
        //非强制升级下，此时为“以后再说”
        if (upgradeLevel == UpgradeOptionalLevel) {
        
            
        }
        
        //强制升级下，此时为“立刻去升级”
        else if (upgradeLevel == UpgradeRequiredLevel){
            
            if (_appPath != nil && _appPath.length != 0) {
                
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_appPath]];
            }
        }
    }
    
    //立刻升级
    else if (buttonIndex == 1) {
        
        if (_appPath != nil && _appPath.length != 0) {
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_appPath]];
        }
    }
    
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    UpgradeLevel upgradeLevel = [_versionInfo[@"status"] integerValue];
    
    if (buttonIndex == 0 && upgradeLevel == UpgradeRequiredLevel) {
        [alertView show];
    }
}

@end
